<?php

/**
 * NOTICE OF LICENSE
 *
 * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
 * 
 * DO NOT USE THIS FILE IN OTHER PLACE.
 *
 * @package   App_User
 * @author    Cheng Wei <berlios.o@gmail.com>
 * @version   $$Id: User.php 20 2010-12-18 09:35:07Z cheng.wei $$
 * @copyright Copyright (c) 2008 Evebit Inc. China (http://www.evebit.com)
 */

/**
 * Resource model for administrator
 * 
 * 
 * @see Backend_Model_Entity_Administrator
 * 
 * @package   App_User
 * @author    Cheng Wei <berlios.o@gmail.com>
 * @version   $$Id: User.php 20 2010-12-18 09:35:07Z cheng.wei $$
 */
class User_Model_Resource_User extends Evebit_Model_Mysql_Abstract {
	
	protected $_datetimeFields = array();
	
	/**
	 * init table
	 */
	protected function _construct() {
		$this->_init('user');
	}
	
	protected function _beforeDelete($object){
		$tableName = $this->getMainTable();
		$fileds = $this->getReadConnection()->describeTable($tableName);
		foreach ($fileds as $key => $value) {
			$length = strpos($key, '_')?strpos($key, '_'):strlen($key);
			$prefix = substr($key, 0, $length);
			if ($prefix == 'upload'){
				$fileName = $object->$key;
				if (file_exists($fileName)){
					unlink($fileName);
				}
				break;
			}
		}
		return $object;
	}
	
	/**
	 * Prepare data for save, password will been prepared
	 *
	 * @param   Evebit_Model_Abstract $object
	 * @return  array
	 */
	protected function _prepareDataForSave(Evebit_Model_Abstract $object) {
		$data = parent::_prepareDataForSave($object);
		if ($object->hasData('new_password')) {
			$data['password'] = $object->getHash($object->getData('new_password'));
		} else if ($object->getId()) {
			if($object->getData('password')!="")
			$data['password'] = $object->getHash($object->getData('password'));
		} else {
			if($object->getData('password')!="")
			$data['password'] = $object->getHash($object->getData('password'));
		}
		
		return $data;
	}

    public function getTableFields($hasId = false){
		$db = $this->getReadConnection ();
		$fields = $db->describeTable($this->getMainTable());
		$fields = array_keys($fields);
		if ($fields[0] == 'id' && !$hasId){
			array_shift($fields);
		}
		return $fields;
	}
}